package cn.baiweigang.uu.api.linearswap;

import cn.baiweigang.uu.api.BaseApi;
import cn.baiweigang.uu.enums.*;
import cn.baiweigang.uu.model.TradeInfo;
import cn.baiweigang.uu.utils.LogUtil;
import cn.baiweigang.uu.utils.StringUtil;
import com.huobi.linearswap.api.enums.DirectionEnum;
import com.huobi.linearswap.api.enums.OffsetEnum;
import com.huobi.linearswap.api.request.trade.*;
import com.huobi.linearswap.api.response.trade.*;
import com.huobi.linearswap.api.service.trade.TradeAPIServiceImpl;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Component
public class TradeApi extends BaseApi {
    private TradeAPIServiceImpl huobiAPIService;

    /**
     * 委托下单
     *
     * @param tradeInfo
     */
    public boolean orderRequest(TradeInfo tradeInfo) {
        //请求平台接口
        if (tradeInfo.getMarginMode() == MarginModeEnum.ISOLATED) {
            return swapOrderRequest(tradeInfo);
        } else {
            LogUtil.logError("第一版只支持逐仓账户");
        }
        return false;
    }

    /**
     * 撤销委托单
     *
     * @param tradeInfo
     */
    public boolean orderCancel(TradeInfo tradeInfo) {
        //请求平台接口
        if (tradeInfo.getMarginMode() == MarginModeEnum.ISOLATED) {
            return swapCancelRequest(tradeInfo);
        } else {
            LogUtil.logError("第一版只支持逐仓账户");
        }
        return false;
    }

    /**
     * 撤销所有委托单
     *
     * @param contractCode
     */
    public boolean orderCancelAll(String accountName, MarginModeEnum marginMode, ContractCodeEnum contractCode) {
        //请求平台接口
        if (marginMode == MarginModeEnum.ISOLATED) {
            return swapCancelallRequest(accountName, contractCode);
        } else {
            LogUtil.logError("第一版只支持逐仓账户");
        }
        return false;
    }

    /**
     * 计划委托下单
     *
     * @param tradeInfo
     */
    public boolean triggerOrderRequest(TradeInfo tradeInfo) {
        //请求平台接口
        if (tradeInfo.getMarginMode() == MarginModeEnum.ISOLATED) {
            return swapTriggerOrderResponse(tradeInfo);
        } else {
            LogUtil.logError("第一版只支持逐仓账户");
        }
        return false;
    }

    /**
     * 撤销计划委托单
     *
     * @param tradeInfo
     */
    public boolean triggerOrderCancel(TradeInfo tradeInfo) {
        //请求平台接口
        if (tradeInfo.getMarginMode() == MarginModeEnum.ISOLATED) {
            return swapTriggerCancelResponse(tradeInfo);
        } else {
            LogUtil.logError("第一版只支持逐仓账户");
        }
        return false;
    }

    /**
     * 撤销所有计划委托单
     *
     * @param contractCode
     */
    public boolean triggerOrderCancelAll(String accountName, MarginModeEnum marginMode, ContractCodeEnum contractCode) {
        //请求平台接口
        if (marginMode == MarginModeEnum.ISOLATED) {
            return swapTriggerCancelallResponse(accountName, contractCode);
        } else {
            LogUtil.logError("第一版只支持逐仓账户");
        }
        return false;
    }


    /**
     * 闪电平仓
     *
     * @param tradeInfo
     */
    public boolean lightningClose(TradeInfo tradeInfo) {
        //请求平台接口
        if (tradeInfo.getMarginMode() == MarginModeEnum.ISOLATED) {
            return swapLightningClosePositionRequest(tradeInfo);
        } else {
            LogUtil.logError("第一版只支持逐仓账户");
        }
        return false;
    }


    /**
     * 从平台更新订单信息
     *
     * @param tradeInfo
     */
    public boolean updateFromHb(TradeInfo tradeInfo) {
        //请求平台接口
        if (tradeInfo.getMarginMode() == MarginModeEnum.ISOLATED) {
            return swapOrderInfoRequest(tradeInfo);
        } else {
            LogUtil.logError("第一版只支持逐仓账户");
        }
        return false;
    }

    /**
     * 查询未成交委托单
     *
     * @param accountName
     * @param contractCode
     * @param tradeType
     * @return
     */
    public List<TradeInfo> queryOpenOrders(String accountName, ContractCodeEnum contractCode,
                                           TradeTypeEnum tradeType) {
        setKeys(accountName);
        SwapOpenordersRequest request = SwapOpenordersRequest.builder()
                .contractCode(contractCode.getCode())
                .tradeType(tradeType.getCode())
                .pageIndex(1)
                .pageSize(20)
                .build();
        SwapOpenordersResponse response =
                huobiAPIService.swapOpenordersRequest(request);
        if (response != null && response.getStatus().equalsIgnoreCase("ok")) {
            LogUtil.logInfo("查询委托订单 成功");
            List<SwapOpenordersResponse.DataBean.OrdersBean> ordersBeanList = response.getData().getOrders();
            return convert2TradeList(ordersBeanList);
        } else {
            LogUtil.logError("查询委托订单 异常");
            LogUtil.logError(response);
        }
        return null;
    }

    /**
     * 查询历史订单 ()
     *
     * @param accountName
     * @param contractCode
     * @param tradeType
     * @return
     */
    public List<TradeInfo> queryHistoryOrders(String accountName, ContractCodeEnum contractCode,
                                              TradeTypeEnum tradeType) {
        setKeys(accountName);
        SwapMatchresultsRequest request = SwapMatchresultsRequest.builder()
                .contractCode(contractCode.getCode())
                .tradeType(tradeType.getCode())
                .createDate(90)
                .pageIndex(1)
                .pageSize(1)
                .build();
        SwapMatchresultsResponse response =
                huobiAPIService.swapMatchresultsRequest(request);
        if (response != null && response.getStatus().equalsIgnoreCase("ok")) {
            List<SwapMatchresultsResponse.DataBean.TradesBean> ordersBeanList = response.getData().getTrades();
            return convert2TradeList3(ordersBeanList);
        } else {
            LogUtil.logError("查询异常");
            LogUtil.logError(response);
        }
        return null;
    }


    /**
     * 查询计划委托-当前委托
     *
     * @param accountName
     * @param contractCode
     * @param tradeType
     * @return
     */
    public List<TradeInfo> queryTriggerOpenOrders(String accountName, ContractCodeEnum contractCode,
                                                  TradeTypeEnum tradeType) {
        setKeys(accountName);
        SwapTriggerOpenordersRequest request = SwapTriggerOpenordersRequest.builder()
                .contractCode(contractCode.getCode())
                .tradeType(tradeType.getCode())
                .pageIndex(1)
                .pageSize(20)
                .build();
        SwapTriggerOpenordersResponse response =
                huobiAPIService.swapTriggerOpenordersResponse(request);
        if (response != null && response.getStatus().equalsIgnoreCase("ok")) {
            List<SwapTriggerOpenordersResponse.DataBean> dataBeanList = response.getData();
            LogUtil.logInfo("查询计划委托-当前委托 查询成功");
            List<TradeInfo> tradeInfoList = new ArrayList<>();
            if (dataBeanList != null && dataBeanList.size() > 0) {
                List<SwapTriggerOpenordersResponse.DataBean.OrdersBean> ordersBeanList = dataBeanList.get(0).getOrders();
                tradeInfoList = convert2TradeList2(ordersBeanList);
            }
            return tradeInfoList;
        } else {
            LogUtil.logError("查询计划委托-当前委托 查询异常");
        }
        LogUtil.logDebug(response);
        return null;
    }

    /**
     * 止盈止损委托下单
     *
     * @param tradeInfo
     */
    public List<TradeInfo> tpslOrderRequest(TradeInfo tradeInfo) {
        //请求平台接口
        if (tradeInfo.getMarginMode() == MarginModeEnum.ISOLATED) {
            return swapTpslOrderRequest(tradeInfo);
        } else {
            LogUtil.logError("第一版只支持逐仓账户");
        }
        return null;
    }

    /**
     * 撤销 止损止盈委托单
     *
     * @param tradeInfo
     */
    public boolean tpslOrderCancel(TradeInfo tradeInfo) {
        //请求平台接口
        if (tradeInfo.getMarginMode() == MarginModeEnum.ISOLATED) {
            return swapTpslCancelResponse(tradeInfo);
        } else {
            LogUtil.logError("第一版只支持逐仓账户");
        }
        return false;
    }

    /**
     * 撤销所有 止盈止损委托单
     *
     * @param contractCode
     */
    public boolean tpslOrderCancelAll(String accountName, MarginModeEnum marginMode, ContractCodeEnum contractCode) {
        //请求平台接口
        if (marginMode == MarginModeEnum.ISOLATED) {
            return swapTpslCancelallResponse(accountName, contractCode);
        } else {
            LogUtil.logError("第一版只支持逐仓账户");
        }
        return false;
    }


    /**
     * 查询止盈止损委托单
     *
     * @param accountName
     * @param contractCode
     * @return
     */
    public List<TradeInfo> queryTpslOpenOrders(String accountName, ContractCodeEnum contractCode) {
        setKeys(accountName);
        SwapTpslOpenordersRequest request = SwapTpslOpenordersRequest.builder()
                .contractCode(contractCode.getCode())
                .pageIndex(1)
                .pageSize(20)
                .build();
        try {
            SwapTpslOpenordersResponse response = huobiAPIService.swapTpslOpenordersResponse(request);
            if (response != null && response.getStatus().equalsIgnoreCase("ok")) {
                List<SwapTpslOpenordersResponse.DataBean> dataBeanList = response.getData();
                LogUtil.logInfo("查询止盈止损单 查询成功");
                List<TradeInfo> tradeInfoList = new ArrayList<>();
                if (dataBeanList != null && dataBeanList.size() > 0) {
                    List<SwapTpslOpenordersResponse.DataBean.OrdersBean> ordersBeanList = dataBeanList.get(0).getOrders();
                    tradeInfoList = convert2TradeList4(ordersBeanList);
                }
                return tradeInfoList;
            } else {
                LogUtil.logError("查询止损止盈委托单 异常");
                LogUtil.logError(response);
            }
        } catch (Throwable e) {
            LogUtil.logError("查询止损止盈委托单 失败 " + e.getMessage());
        }
        return null;

    }

    /**
     * 查询开仓单对应的止盈止损委托单
     *
     * @param accountName
     * @param contractCode
     * @return
     */
    public List<TradeInfo> queryRelationTpslOrder(String accountName, ContractCodeEnum contractCode, long orderId) {
        setKeys(accountName);
        try {
            SwapRelationTpslOrderRequest request = SwapRelationTpslOrderRequest.builder()
                    .contractCode(contractCode.getCode())
                    .orderId(orderId)
                    .build();
            SwapRelationTpslOrderResponse response = huobiAPIService.swapRelationTpslOrderResponse(request);
            List<SwapRelationTpslOrderResponse.DataBean> dataBeanList = response.getData();
            LogUtil.logInfo("查询开舱单关联止盈止损单 查询成功");
            List<TradeInfo> tradeInfoList = new ArrayList<>();
            if (dataBeanList != null && dataBeanList.size() > 0) {
                List<SwapRelationTpslOrderResponse.DataBean.TpslOrderInfoBean> tpslOrderInfoBeanList = dataBeanList.get(0).getTpslOrderInfo();
                tradeInfoList = convert2TradeList5(tpslOrderInfoBeanList);
            }
            return tradeInfoList;
        } catch (Throwable e) {
            LogUtil.logError("查询止损止盈委托单 失败 " + e.getMessage());
        }
        return null;

    }

    private List<TradeInfo> convert2TradeList5(List<SwapRelationTpslOrderResponse.DataBean.TpslOrderInfoBean> tpslOrderInfoBeanList) {
        List<TradeInfo> tradeInfoList = new ArrayList<>();
        for (SwapRelationTpslOrderResponse.DataBean.TpslOrderInfoBean dataBean : tpslOrderInfoBeanList) {
            TradeInfo tradeInfo = new TradeInfo();
            tradeInfo.setVolume(dataBean.getVolume().longValue());
            tradeInfo.setTpslOrderType(dataBean.getTpslOrderType());
            tradeInfo.setDirection(cn.baiweigang.uu.enums.DirectionEnum.byCode(dataBean.getDirection()));
            tradeInfo.setOrderId(dataBean.getOrderId());
            tradeInfo.setOrdeIdStr(dataBean.getOrderIdStr() + "");
            tradeInfo.setTriggerType(TriggerTypeEnum.byCode(dataBean.getTriggerType()));
            tradeInfo.setTriggerPrice(dataBean.getTriggerPrice());
            tradeInfo.setPrice(dataBean.getOrderPrice());
            tradeInfo.setCreatedGmt(dataBean.getCreatedAt());
            tradeInfo.setOrderPriceType(OrderPriceTypeEnum.byCode(dataBean.getOrderPriceType()));
            tradeInfo.setStatus(TradeStatusEnum.byCode(dataBean.getStatus()));
            tradeInfo.setRelationTpslOrderId(dataBean.getRelationTpslOrderId());
            tradeInfo.setCanceledGmt(dataBean.getCanceledAt());

            tradeInfoList.add(tradeInfo);
        }
        return tradeInfoList;
    }

    private List<TradeInfo> convert2TradeList4(List<SwapTpslOpenordersResponse.DataBean.OrdersBean> ordersBeanList) {
        List<TradeInfo> tradeInfoList = new ArrayList<>();
        for (SwapTpslOpenordersResponse.DataBean.OrdersBean dataBean : ordersBeanList) {
            TradeInfo tradeInfo = new TradeInfo();
            tradeInfo.setContractCode(ContractCodeEnum.byCode(dataBean.getContractCode()));
            tradeInfo.setMarginMode(MarginModeEnum.byCode(dataBean.getMarginMode()));
            tradeInfo.setVolume(dataBean.getVolume().longValue());
            tradeInfo.setTpslOrderType(dataBean.getTpslOrderType());
            tradeInfo.setDirection(cn.baiweigang.uu.enums.DirectionEnum.byCode(dataBean.getDirection()));
            tradeInfo.setOrderId(dataBean.getOrderId());
            tradeInfo.setOrdeIdStr(dataBean.getOrderIdStr() + "");
            tradeInfo.setOrderSource(dataBean.getOrderSource());
            tradeInfo.setTriggerType(TriggerTypeEnum.byCode(dataBean.getTriggerType()));
            tradeInfo.setTriggerPrice(dataBean.getTriggerPrice());
            tradeInfo.setCreatedGmt(dataBean.getCreatedAt());
            tradeInfo.setOrderPriceType(OrderPriceTypeEnum.byCode(dataBean.getOrderPriceType()));
            tradeInfo.setPrice(dataBean.getOrderPrice());
            tradeInfo.setStatus(TradeStatusEnum.byCode(dataBean.getStatus()));
            tradeInfo.setSourceOrderId(dataBean.getSourceOrderId());
            tradeInfo.setRelationTpslOrderId(dataBean.getRelationTpslOrderId());
            tradeInfoList.add(tradeInfo);
        }
        return tradeInfoList;
    }

    private List<TradeInfo> convert2TradeList3(List<SwapMatchresultsResponse.DataBean.TradesBean> ordersBeanList) {
        List<TradeInfo> tradeInfoList = new ArrayList<>();
        for (SwapMatchresultsResponse.DataBean.TradesBean dataBean : ordersBeanList) {
            TradeInfo tradeInfo = new TradeInfo();
            tradeInfo.setContractCode(ContractCodeEnum.byCode(dataBean.getContractCode()));
            tradeInfo.setMarginMode(MarginModeEnum.byCode(dataBean.getMarginMode()));
            tradeInfo.setVolume(dataBean.getTradeVolume().longValue());
            tradeInfo.setPrice(dataBean.getTradePrice());
            tradeInfo.setDirection(cn.baiweigang.uu.enums.DirectionEnum.byCode(dataBean.getDirection()));
            tradeInfo.setOffset(cn.baiweigang.uu.enums.OffsetEnum.byCode(dataBean.getOffset()));
            tradeInfo.setOrderId(dataBean.getOrderId());
            tradeInfo.setOrdeIdStr(dataBean.getOrderIdStr() + "");
            tradeInfo.setCreatedGmt(dataBean.getCreateDate());
            tradeInfo.setTradeVolume(dataBean.getTradeVolume());
            tradeInfo.setTradeTurnover(dataBean.getTradeTurnover());
            tradeInfo.setFee(new BigDecimal(dataBean.getTradeFee()));
            tradeInfo.setOrderSource(dataBean.getOrderSource());
            tradeInfo.setRealProfit(dataBean.getRealProfit());
            tradeInfo.setRole(dataBean.getRole());

            tradeInfoList.add(tradeInfo);
        }
        return tradeInfoList;
    }

    private List<TradeInfo> convert2TradeList2(List<SwapTriggerOpenordersResponse.DataBean.OrdersBean> ordersBeanList) {
        List<TradeInfo> tradeInfoList = new ArrayList<>();
        for (SwapTriggerOpenordersResponse.DataBean.OrdersBean dataBean : ordersBeanList) {
            TradeInfo tradeInfo = new TradeInfo();
            tradeInfo.setContractCode(ContractCodeEnum.byCode(dataBean.getContractCode()));
            tradeInfo.setMarginMode(MarginModeEnum.byCode(dataBean.getMarginMode()));
            tradeInfo.setVolume(dataBean.getVolume().longValue());
            tradeInfo.setPrice(dataBean.getTriggerPrice());
            tradeInfo.setOrderPriceType(OrderPriceTypeEnum.byCode(dataBean.getOrderPriceType()));
            tradeInfo.setDirection(cn.baiweigang.uu.enums.DirectionEnum.byCode(dataBean.getDirection()));
            tradeInfo.setOffset(cn.baiweigang.uu.enums.OffsetEnum.byCode(dataBean.getOffset()));
            tradeInfo.setLeverRate(dataBean.getLeverRate());
            tradeInfo.setOrderId(dataBean.getOrderId());
            tradeInfo.setOrdeIdStr(dataBean.getOrderIdStr() + "");
            tradeInfo.setCreatedGmt(dataBean.getCreatedAt());
            tradeInfo.setStatus(TradeStatusEnum.byCode(dataBean.getStatus()));
            tradeInfo.setOrderSource(dataBean.getOrderSource());
            tradeInfoList.add(tradeInfo);
        }
        return tradeInfoList;
    }


    private List<TradeInfo> convert2TradeList(List<SwapOpenordersResponse.DataBean.OrdersBean> ordersBeanList) {
        List<TradeInfo> tradeInfoList = new ArrayList<>();
        for (SwapOpenordersResponse.DataBean.OrdersBean dataBean : ordersBeanList) {
            TradeInfo tradeInfo = new TradeInfo();
            tradeInfo.setContractCode(ContractCodeEnum.byCode(dataBean.getContractCode()));
            tradeInfo.setMarginMode(MarginModeEnum.byCode(dataBean.getMarginMode()));
            tradeInfo.setVolume(dataBean.getVolume().longValue());
            tradeInfo.setPrice(dataBean.getPrice());
            tradeInfo.setOrderPriceType(OrderPriceTypeEnum.byCode(dataBean.getOrderPriceType()));
            tradeInfo.setDirection(cn.baiweigang.uu.enums.DirectionEnum.byCode(dataBean.getDirection()));
            tradeInfo.setOffset(cn.baiweigang.uu.enums.OffsetEnum.byCode(dataBean.getOffset()));
            tradeInfo.setLeverRate(dataBean.getLeverRate());
            tradeInfo.setOrderId(dataBean.getOrderId());
            tradeInfo.setOrdeIdStr(dataBean.getOrderIdStr() + "");
            tradeInfo.setClientOrderId(dataBean.getClientOrderId() != null ?
                    dataBean.getClientOrderId().toString() : null);
            tradeInfo.setCreatedGmt(dataBean.getCreatedAt());
            tradeInfo.setTradeVolume(dataBean.getTradeVolume());
            tradeInfo.setTradeTurnover(dataBean.getTradeTurnover());
            tradeInfo.setFee(dataBean.getFee());
            tradeInfo.setTradeAvgPrice(dataBean.getTradeAvgPrice());
            tradeInfo.setMarginFrozen(dataBean.getMarginFrozen());
            tradeInfo.setProfit(dataBean.getProfit());
            tradeInfo.setStatus(TradeStatusEnum.byCode(dataBean.getStatus()));
            tradeInfo.setOrderSource(dataBean.getOrderSource());
            tradeInfo.setIstpsl(dataBean.getIsTpsl());
            tradeInfo.setRealProfit(dataBean.getRealProfit());

            tradeInfoList.add(tradeInfo);
        }
        return tradeInfoList;
    }

    private boolean swapCancelRequest(TradeInfo tradeInfo) {
        setKeys(tradeInfo.getAccountName());
        SwapCancelRequest request = SwapCancelRequest.builder()
                .contractCode(tradeInfo.getContractCode().getCode())
//                .orderId(tradeInfo.getOrdeId() + "")
                .clientOrderId(tradeInfo.getClientOrderId())
                .build();
        try {
            SwapCancelResponse response =
                    huobiAPIService.swapCancelRequest(request);
            if (response != null && response.getStatus().equalsIgnoreCase("ok") &&
                    StringUtil.isNotBlank(response.getData().getSuccesses())) {
                LogUtil.logInfo("提交撤销委托单请求-成功");
                LogUtil.logDebug(response);
                return true;
            } else {
                LogUtil.logError("提交撤销委托单-异常");
            }
        } catch (Throwable e) {
            LogUtil.logError("取消委托订单 提交失败 " + e.getMessage());
        }
        return false;
    }

    private boolean swapTriggerCancelResponse(TradeInfo tradeInfo) {
        setKeys(tradeInfo.getAccountName());
        SwapTriggerCancelRequest request = SwapTriggerCancelRequest.builder()
                .orderId(tradeInfo.getOrderId() + "")
                .contractCode(tradeInfo.getContractCode().getCode())
                .build();
        try {
            SwapTriggerCancelResponse response = huobiAPIService.swapTriggerCancelResponse(request);
            if (response != null && response.getStatus().equalsIgnoreCase("ok")) {
                LogUtil.logInfo("提交撤销-计划委托单-请求成功");
                LogUtil.logDebug(response);
                return true;
            } else {
                LogUtil.logError("提交撤销-计划委托单-异常");
                LogUtil.logError(response);
            }
        } catch (Throwable e) {
            LogUtil.logError("计划委托订单 撤销失败 " + e.getMessage());
        }
        return false;
    }


    private boolean swapCancelallRequest(String accountName, ContractCodeEnum contractCode) {
        setKeys(accountName);
        SwapCancelallRequest request = SwapCancelallRequest.builder()
                .contractCode(contractCode.getCode())
                .build();
        try {
            SwapCancelallResponse response =
                    huobiAPIService.swapCancelallRequest(request);
            if (response != null && response.getStatus().equalsIgnoreCase("ok") &&
                    StringUtil.isNotBlank(response.getData().getSuccesses())) {
                LogUtil.logInfo("撤销所有委托单 提交成功");
                LogUtil.logInfo(response);
                return true;
            } else {
                LogUtil.logError("撤销所有委托单 提交异常");
            }
        } catch (Throwable e) {
            LogUtil.logError("撤销所有委托单 提交失败 " + e.getMessage());
        }
        return false;

    }

    private boolean swapTriggerCancelallResponse(String accountName, ContractCodeEnum contractCode) {
        setKeys(accountName);
        try {
            SwapTriggerCancelallRequest request = SwapTriggerCancelallRequest.builder()
                    .contractCode(contractCode.getCode())
                    .build();
            SwapTriggerCancelallResponse response =
                    huobiAPIService.swapTriggerCancelallResponse(request);
            if (StringUtil.isNotBlank(response.getData().get(0).getSuccesses())) {
                LogUtil.logInfo("撤销所有-计划委托单 提交成功");
                LogUtil.logInfo(response);
            } else {
                LogUtil.logError("撤销所有-计划委托单 提交异常");
            }
        } catch (Throwable e) {
            LogUtil.logError("撤销所有-计划委托单 提交失败 " + e.getMessage());
        }
        return false;
    }

    private boolean swapOrderInfoRequest(TradeInfo tradeInfo) {
        setKeys(tradeInfo.getAccountName());
        SwapOrderInfoRequest request = SwapOrderInfoRequest.builder()
                .contractCode(tradeInfo.getContractCode().getCode())
                .clientOrderId(tradeInfo.getClientOrderId())
//                .orderId(tradeInfo.getOrdeId() + "")
                .build();
        if (StringUtil.isBlank(request.getClientOrderId())) {
            request.setOrderId(tradeInfo.getOrderId() + "");
        }
        try {
            SwapOrderInfoResponse response =
                    huobiAPIService.swapOrderInfoRequest(request);
            if (response != null && response.getStatus().equalsIgnoreCase("ok")) {
                List<SwapOrderInfoResponse.DataBean> dataList = response.getData();
                if (dataList == null || dataList.size() != 1) {
                    LogUtil.logError("查询订单结果异常 ");
                    LogUtil.logInfo(dataList);
                }
                SwapOrderInfoResponse.DataBean dataBean = dataList.get(0);
                tradeInfo.setContractCode(ContractCodeEnum.byCode(dataBean.getContractCode()));
                tradeInfo.setVolume(dataBean.getVolume().longValue());
                tradeInfo.setPrice(dataBean.getPrice());
                tradeInfo.setIstpsl(dataBean.getIsTpsl());
                tradeInfo.setOrderPriceType(OrderPriceTypeEnum.byCode(dataBean.getOrderPriceType()));
                tradeInfo.setDirection(cn.baiweigang.uu.enums.DirectionEnum.byCode(dataBean.getDirection()));
                tradeInfo.setOffset(cn.baiweigang.uu.enums.OffsetEnum.byCode(dataBean.getOffset()));
                tradeInfo.setLeverRate(dataBean.getLeverRate());
                tradeInfo.setOrderId(dataBean.getOrderId());
                tradeInfo.setMarginMode(MarginModeEnum.byCode(dataBean.getMarginMode()));
                tradeInfo.setOrdeIdStr(dataBean.getOrderIdStr());
                tradeInfo.setClientOrderId(dataBean.getClientOrderId() + "");
                tradeInfo.setCreatedGmt(dataBean.getCreatedAt());

                tradeInfo.setTradeVolume(dataBean.getTradeVolume());
                tradeInfo.setTradeTurnover(dataBean.getTradeTurnover());
                tradeInfo.setFee(dataBean.getFee());
                tradeInfo.setTradeAvgPrice(dataBean.getTradeAvgPrice());
                tradeInfo.setMarginFrozen(dataBean.getMarginFrozen());
                tradeInfo.setProfit(dataBean.getProfit());
                tradeInfo.setStatus(TradeStatusEnum.byCode(dataBean.getStatus()));
                tradeInfo.setOrderSource(dataBean.getOrderSource());
                tradeInfo.setCanceledGmt(dataBean.getCanceledAt());
                tradeInfo.setIstpsl(dataBean.getIsTpsl());
                tradeInfo.setRealProfit(dataBean.getRealProfit());
                LogUtil.logInfo("从HB服务端查询单据成功");
                LogUtil.logDebug(tradeInfo);
                return true;
            } else {
                LogUtil.logError("获取订单信息异常");
                LogUtil.logError(response);
            }
        } catch (Throwable e) {
            LogUtil.logError("获取订单信息异常 " + e.getMessage());
        }
        return false;
    }

    private boolean swapLightningClosePositionRequest(TradeInfo tradeInfo) {
        setKeys(tradeInfo.getAccountName());
        SwapLightningClosePositionRequest request = SwapLightningClosePositionRequest.builder()
                .contractCode(tradeInfo.getContractCode().getCode())
                .direction(tradeInfo.getDirection().getCode())
                .volume((int) tradeInfo.getVolume())
                .build();
        if (tradeInfo.getClientOrderId() != null) {
            request.setClientOrderId(Long.valueOf(tradeInfo.getClientOrderId()));
        }
        try {
            LogUtil.logInfo("闪电平仓请求");
            LogUtil.logInfo(request);
            SwapLightningClosePositionResponse response =
                    huobiAPIService.swapLightningClosePositionRequest(request);
            if (response != null && response.getStatus().equalsIgnoreCase("ok")) {
                tradeInfo.setOrderId(response.getData().getOrderId());
                tradeInfo.setOrdeIdStr(response.getData().getOrderIdStr());
                if (response.getData().getClientOrderId() != null) {
                    tradeInfo.setClientOrderId(response.getData().getClientOrderId() + "");
                }
                LogUtil.logInfo("闪电平仓下单成功");
                LogUtil.logDebug(response);
                return true;
            } else {
                LogUtil.logError("闪电下单异常");
                LogUtil.logError(response);
            }
        } catch (Throwable e) {
            LogUtil.logError("闪电下单异常 " + e.getMessage());
        }
        return false;
    }

    private boolean swapTriggerOrderResponse(TradeInfo tradeInfo) {
        setKeys(tradeInfo.getAccountName());
        SwapTriggerOrderRequest request = SwapTriggerOrderRequest.builder()
                .contractCode(tradeInfo.getContractCode().getCode())
                .triggerType(tradeInfo.getTriggerType().getCode())
                .triggerPrice(tradeInfo.getTriggerPrice())
                .orderPrice(tradeInfo.getPrice())
                .orderPriceType(tradeInfo.getOrderPriceType().getCode())
                .volume(new BigDecimal(tradeInfo.getVolume()))
                .direction(tradeInfo.getDirection() == cn.baiweigang.uu.enums.DirectionEnum.SELL ?
                        DirectionEnum.SELL : DirectionEnum.BUY)
                .offset(tradeInfo.getOffset() == cn.baiweigang.uu.enums.OffsetEnum.OPEN ?
                        OffsetEnum.OPEN : OffsetEnum.CLOSE)
                .leverRate(tradeInfo.getLeverRate())
                .build();
        try {
            SwapTriggerOrderResponse response = huobiAPIService.swapTriggerOrderResponse(request);
            if (response != null && response.getStatus().equalsIgnoreCase("ok")) {
                tradeInfo.setOrderId(response.getData().get(0).getOrderId());
                tradeInfo.setOrdeIdStr(response.getData().get(0).getOrderIdStr());
                LogUtil.logInfo("计划委托下单成功 ");
                LogUtil.logDebug(response);
                return true;
            } else {
                LogUtil.logError("计划委托下单异常");
                LogUtil.logError(response);
            }
        } catch (Throwable e) {
            LogUtil.logError("计划委托下单 失败 " + e.getMessage());
        }
        return false;
    }

    private boolean swapOrderRequest(TradeInfo tradeInfo) {
        setKeys(tradeInfo.getAccountName());
        try {
            SwapOrderRequest request = SwapOrderRequest.builder()
                    .contractCode(tradeInfo.getContractCode().getCode())
                    .volume(tradeInfo.getVolume())
                    .price(tradeInfo.getPrice())
                    .direction(tradeInfo.getDirection() == cn.baiweigang.uu.enums.DirectionEnum.SELL ?
                            DirectionEnum.SELL : DirectionEnum.BUY)
                    .offset(tradeInfo.getOffset() == cn.baiweigang.uu.enums.OffsetEnum.OPEN ?
                            OffsetEnum.OPEN : OffsetEnum.CLOSE)
                    .leverRate(tradeInfo.getLeverRate())
                    .orderPriceType(tradeInfo.getOrderPriceType().getCode())
                    .tpTriggerPrice(tradeInfo.getTpTriggerPrice())
                    .tpOrderPrice(tradeInfo.getTpOrderPrice())
                    .tpOrderPriceType(tradeInfo.getTpOrderPriceType() != null ?
                            tradeInfo.getTpOrderPriceType().getCode() : null)
                    .slTriggerPrice(tradeInfo.getSlTriggerPrice())
                    .slOrderPrice(tradeInfo.getSlOrderPrice())
                    .slOrderPriceType(tradeInfo.getSlOrderPriceType() != null ?
                            tradeInfo.getSlOrderPriceType().getCode() : null)
                    .clientOrderId(Long.valueOf(tradeInfo.getClientOrderId()))
                    .build();


            SwapOrderResponse response =
                    huobiAPIService.swapOrderRequest(request);
            if (response != null && response.getStatus().equalsIgnoreCase("ok")) {
                tradeInfo.setOrderId(response.getData().getOrderId());
                tradeInfo.setOrdeIdStr(response.getData().getOrderIdStr());
                LogUtil.logInfo("下单成功 ");
                LogUtil.logDebug(tradeInfo);
                return true;
            } else {
                LogUtil.logError("下单异常");
                LogUtil.logError(response);
            }
        } catch (Throwable e) {
            LogUtil.logError("委托下单失败 " + e.getMessage());
        }
        return false;
    }

    private boolean swapTpslCancelResponse(TradeInfo tradeInfo) {
        setKeys(tradeInfo.getAccountName());
        try {
            SwapTpslCancelRequest request = SwapTpslCancelRequest.builder()
                    .contractCode(tradeInfo.getContractCode().getCode())
                    .orderId(tradeInfo.getOrderId() + "")
                    .build();
            SwapTpslCancelResponse response = huobiAPIService.swapTpslCancelResponse(request);
            if (response.getData() != null && response.getData().size() == 1) {
                LogUtil.logInfo("提交撤销 止盈止损单请求-成功");
                LogUtil.logDebug(response);
                return true;
            } else {
                LogUtil.logError("提交撤销 止盈止损单-失败");
            }
        } catch (Throwable e) {
            LogUtil.logError("提交撤销 止盈止损单-异常 " + e.getMessage());
        }
        return false;
    }

    private List<TradeInfo> swapTpslOrderRequest(TradeInfo tradeInfo) {
        setKeys(tradeInfo.getAccountName());
        try {
            SwapTpslOrderRequest request = SwapTpslOrderRequest.builder()
                    .contractCode(tradeInfo.getContractCode().getCode())
                    .direction(tradeInfo.getDirection().getCode())
                    .volume(BigDecimal.valueOf(tradeInfo.getVolume()))
                    .tpTriggerPrice(tradeInfo.getTpTriggerPrice())
                    .tpOrderPrice(tradeInfo.getTpOrderPrice())
                    .slTriggerPrice(tradeInfo.getSlTriggerPrice())
                    .slOrderPrice(tradeInfo.getSlOrderPrice())
                    .build();
            if (tradeInfo.getTpOrderPriceType() != null) {
                request.setTpOrderPriceType(tradeInfo.getTpOrderPriceType().getCode());
            }
            if (tradeInfo.getSlOrderPriceType() != null) {
                request.setSlOrderPriceType(tradeInfo.getSlOrderPriceType().getCode());
            }
            SwapTpslOrderResponse response = huobiAPIService.swapTpslOrderResponse(request);
            if (response.getData() != null && response.getData().size() == 1) {
                List<TradeInfo> tradeInfoList = new ArrayList<>();
                List<SwapTpslOrderResponse.DataBean> dataBeanList = response.getData();
                List<SwapTpslOrderResponse.DataBean.tpOrderBean> tpOrderBeanList = dataBeanList.get(0).getTpOrder();
                TradeInfo tradeInfo1 = new TradeInfo();
                tradeInfo1.setTpslOrderType("tp");
                tradeInfo1.setOrderId(tpOrderBeanList.get(0).getOrderId());
                tradeInfo1.setOrdeIdStr(tpOrderBeanList.get(0).getOrderIdStr());
                tradeInfoList.add(tradeInfo1);

                List<SwapTpslOrderResponse.DataBean.slOrderBean> slOrderBeanList = dataBeanList.get(0).getSlOrder();
                TradeInfo tradeInfo2 = new TradeInfo();
                tradeInfo2.setTpslOrderType("sl");
                tradeInfo2.setOrderId(slOrderBeanList.get(0).getOrderId());
                tradeInfo2.setOrdeIdStr(slOrderBeanList.get(0).getOrderIdStr());
                tradeInfoList.add(tradeInfo2);

                LogUtil.logInfo("止盈止损 下单成功 ");
                LogUtil.logDebug(tradeInfo);
                return tradeInfoList;
            } else {
                LogUtil.logError("止盈止损 下单异常");
                LogUtil.logError(response);
            }
        } catch (Throwable e) {
            LogUtil.logError("止盈止损  下单失败 ");
            LogUtil.logError(e.toString());
        }
        return null;
    }

    private boolean swapTpslCancelallResponse(String accountName, ContractCodeEnum contractCode) {
        setKeys(accountName);
        try {
            SwapTpslCancelallRequest request = SwapTpslCancelallRequest.builder()
                    .contractCode(contractCode.getCode())
                    .build();
            SwapTpslCancelallResponse response = huobiAPIService.swapTpslCancelallResponse(request);
            LogUtil.logInfo("提交撤销 所有止盈止损单请求-成功");
            LogUtil.logInfo(response);
            return true;
        } catch (Throwable e) {
            LogUtil.logError("提交撤销 所有止盈止损单-异常 " + e.getMessage());
        }
        return false;
    }

    private void setKeys(String accountName) {
        loadByAccountName(accountName);
        huobiAPIService = new TradeAPIServiceImpl(apiKeyInfo.getApiKey(),
                apiKeyInfo.getSecretKey());
    }
}
